package com.rk.kbk.controller;

import com.rk.kbk.common.JsonResp;
import com.rk.kbk.common.PubLib;
import com.rk.kbk.common.SqlToResult;
import com.rk.kbk.dao.AddressDao;
import com.rk.kbk.dao.ContactsDao;
import com.rk.kbk.dao.UserDao;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.Address;
import com.rk.kbk.model.Contacts;
import com.rk.kbk.model.User;
import com.rk.kbk.service.UserService;
import org.apache.log4j.Logger;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.util.*;

/**
 * @AddressController
 * @地址Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/address")
public class AddressController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ContactsDao contactsDao;
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private SqlToResult sqlToResult;
    @Autowired
    private UserService userService;
    /**
     * @添加/修改地址
     * @param address
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateAddress",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateAddress(@RequestBody Address address){
        log.debug("添加/修改地址");
        if(address.getId()!=null  && !"".equals(String.valueOf(address.getId()))){
            Address address1=addressDao.findOne(address.getId());
            address1.setRealName(address.getRealName());
            address1.setSex(address.getSex());
            address1.setPhone(address.getPhone());
            address1.setProvince(address.getProvince());
            address1.setCity(address.getCity());
            address1.setCounty(address.getCounty());
            address1.setAddressDetail(address.getAddressDetail());
            address1.setLat(address.getLat());
            address1.setLng(address.getLng());
            address1.setStatus(1);
            address1.setLevel(1);
            address1.setType(1);
            addressDao.save(address1);
        }else {
            addressDao.save(address);
        }
        Contacts contacts=new Contacts();
        contacts.setAddress(address);
        contacts.setPhone(address.getPhone());
        contactsDao.save(contacts);
        return JsonResp.ok();
    }

    /**
     * @批量添加/修改地址
     * @param addresss
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomeAddress",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeAddress(@RequestBody List<Address> addresss){
        log.debug("批量添加/修改地址");
        addressDao.save(addresss);
        return JsonResp.ok();
    }

    /**
     * @获取地址详情-ByAddressId
     * @param addressId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findAddressDetailsByAddressId",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findAddressDetailsByAddressId(Long addressId,int status) {
        log.debug("获取地址详情-ByAddressId");
        Map map =new HashMap<>();
         Address address=addressDao.findByIdAndStatus(addressId,status);
        if(address!=null){
            map.put("id",address.getId());
            map.put("province",address.getProvince());
            map.put("city",address.getCity());
            map.put("county",address.getCounty());
            map.put("addressDetail",address.getAddressDetail());
            map.put("sex",address.getSex());
            map.put("realName",address.getRealName());
            map.put("phone",address.getPhone());
            map.put("lng",address.getLng());
            map.put("lat",address.getLat());
            map.put("areaCode",address.getAreaCode());
        }else {
            return  JsonResp.fa("没找到相应的地址信息");
        }


        return JsonResp.ok(map);
    }


    /**
     * @根据用户id查找地址
     * @param userId 用户id
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addressByUserId",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addressFindByUserId(Long userId){
        log.debug("根据用户id查找地址");
        User user = userDao.findOne(userId);
        Long addressId=user.getAddress();
        return JsonResp.ok(addressDao.findOne(addressId));
    }



    /**
     * @分页查询地址(jpa方式)
     * @param address 分页条件
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/page",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageAddressJpa(@RequestBody(required = false) Address address, Integer pageNum, Integer pageSize) {
        log.debug("分页查询地址(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        if (null == address) {
            page = addressDao.findAll(pageable); //无条件分页
        }/*else{
            final String condition =  address.getUserName();
            page = addressDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        if (StringUtils.isNotBlank(condition)) {
                            expressions.add(cb.like(root.<String>get("condition"), "%"+ condition +"%"));
                        }
                        return predicate;
                    }, pageable);
        }*/
        List<Address> content = page.getContent();
        for (Address address1 : content) {
        }
        return JsonResp.ok(new PageDto(page));
    }

    /**
     * @分页查询地址(jpa方式)
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/addressPage",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageAddressJpa2( Integer pageNum, Integer pageSize) {
        log.debug("分页查询地址(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        page = addressDao.findAll( pageable); //无条件分页
        return JsonResp.ok(new PageDto(page));
    }


    /**
     * @删除地址-one(永久)
     * @param addressId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteAddressOne",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteAddressOne(Long addressId) {
        log.debug("删除地址-one(永久)");
        addressDao.delete(addressId);
        return JsonResp.ok();
    }

    /**
     * @批量删除地址(永久)
     * @param addresss
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomeAddress",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomeAddress(@RequestBody List<Address> addresss) {
        log.debug("批量删除地址(永久)");
        addressDao.delete(addresss);
        return JsonResp.ok();
    }


    /**
     * @分页查询客户通讯录(原生sql)
     * @param search  模糊查询
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/pageSql",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageAddressSql(Integer pageNum, Integer pageSize,String search) {
        log.debug("分页查询客户通讯录(原生sql)");

        String sql = "FROM `address` where  phone like '%"+search+"%' and type=1 and status=1 ";
        Query query = entityManager.createNativeQuery("SELECT *" + sql);

        BigInteger count_number = null;
        //总记录数
        Query query_number = entityManager.createNativeQuery("SELECT COUNT(1) " + sql);
        count_number = (BigInteger) query_number.getSingleResult();
        long total = count_number.longValue();
        //分页
        if ((pageNum-1) >= 0) {
            query.setFirstResult((pageNum-1) * pageSize);
        }
        if (pageSize > 0) {
            query.setMaxResults(pageSize);
        }
        entityManager.close();

        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map> mapList = new ArrayList<>();
        query.getResultList().forEach(n -> mapList.add(PubLib.copyObject(PubLib.convert(n), Map.class)));

        return JsonResp.ok(new PageDto(pageNum, pageSize, mapList, total));
    }

    /**
     * @客户统计
     * @param search 模糊查询
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addressSum",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addressSum( String search) {
        log.debug("客户统计");
        String sql = "select count(id) as sum FROM `address` where  phone like '%"+search+"%' and type=1 ";
        Object resultList = sqlToResult.getResultList(sql, "one");
        Map map = PubLib.copyObject(resultList, Map.class);
        return JsonResp.ok(map);
    }

    /**
     * @客户详情
     * @param  id 客户id
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addressDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addressDetails( Long id) {
        log.debug("客户详情");
        return JsonResp.ok(addressDao.findOne(id));
    }

    /**
     * @商户地址详情（地图）
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addressShop",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addressShop(String areaCode) {
        log.debug("商户地址详情（地图）");
        String sql=" select a.nick_name as shopname, b.id as id,b.lng as lng,b.lat as lat from user a left join address b  on a.address = b.id WHERE b.type=2 and a.is_register=1 and b.area_code = "+areaCode+" ";
        List<String> resultList = (List<String>) sqlToResult.getResultList(sql);
        List<Map> list = new ArrayList<>();
        for (Object string : resultList) {
            Map map = PubLib.copyObject(string, Map.class);
            list.add(map);
        }
        return JsonResp.ok(resultList);
    }

    /**
     * @编辑用户所属区域
     * @param  userId 用户id
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/updateUserAddress",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp updateUserAddress(@RequestBody Address addresss ,Long userId) {
        log.debug("编辑用户所属区域");
        User user = userDao.findOne(userId);
        Long addressId = user.getAddress();
        Address a = addressDao.findOne(addressId);
        a.setAddressDetail(addresss.getAddressDetail());
        a.setProvince(addresss.getProvince());
        a.setCity(addresss.getCity());
        a.setCounty(addresss.getCounty());
        a.setAreaCode(addresss.getAreaCode());
        //修改商家定位坐标
        if(user.getUserType()==3){
            a.setLng(addresss.getLng());
            a.setLat(addresss.getLat());
        }
        addressDao.save(a);
        return JsonResp.ok();
    }

    /**
     * @获取用户地址列表(微信端)
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findUserAddressList",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findUserAddressList() {
        log.debug("获取用户地址列表");
        User user=userService.currentUser();
       List<Address> addresses=addressDao.findByPhoneAndLevel(user.getPhone(),1);
        return JsonResp.ok(addresses);
    }

    /**
     * @删除地址
     * @param  addressId 用户id
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteAddress",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteAddress(Long addressId) {
        log.debug("获取用户地址列表");
        addressDao.delete(addressId);
        return JsonResp.ok();
    }

    /**
     * @删除地址
     * @param  addressId 用户id
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/seeAddress",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp seeAddress(Long addressId) {
        log.debug("获取用户地址列表");
        Address address =addressDao.findOne(addressId);
        return JsonResp.ok(address);
    }



}
